package com.lovely3x.paymentlibrary.alipay;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import com.alipay.sdk.app.PayTask;
import com.lovely3x.common.BuildConfig;
import com.lovely3x.common.activities.CommonActivity;
import com.lovely3x.common.managements.pay.IPayCallBack;
import com.lovely3x.common.managements.pay.InitHook;
import com.lovely3x.common.managements.pay.PayAction;
import com.lovely3x.common.managements.pay.PayRequest;
import com.lovely3x.common.managements.pay.PaymentManager;
import com.lovely3x.common.utils.ALog;

import java.util.Map;

/**
 * 支付宝 2.0支付
 * Created by lovely3x on 16/9/22.
 */
public class AliPay2Action implements PayAction, InitHook<PaymentManager> {

    public static final AliPay2Action INSTANCE = new AliPay2Action();

    /**
     * 支付宝支付业务：入参app_id
     */
    public static final String APPID = BuildConfig.ALIPAY_APPID;

    /**
     * 商户私钥，pkcs8格式
     */
    public static final String RSA_PRIVATE = BuildConfig.ALIPAY_RSA_PRIVATE;

    private static final int SDK_PAY_FLAG = 1;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult2 payResult = new PayResult2((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        PaymentManager.getInstance().notifyPayResult(IPayCallBack.PayMethod.AliPay, IPayCallBack.PayResult.Successful);
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        PaymentManager.getInstance().notifyPayResult(IPayCallBack.PayMethod.AliPay, IPayCallBack.PayResult.Fail);
                    }
                    break;
                }
            }
        }
    };


    @Override
    public boolean pay(PayRequest payRequest, IPayCallBack.PayMethod payMethod) {
        if (payMethod == IPayCallBack.PayMethod.AliPay2 && payRequest instanceof AliPayPayRequest) {
            payV2((AliPayPayRequest) payRequest, ((AliPayPayRequest) payRequest).mActivity);
            return true;
        }
        return false;
    }


    /**
     * 支付宝支付业务
     */
    public void payV2(AliPayPayRequest payRequest, final CommonActivity context) {

        /**
         * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
         * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
         * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
         *
         * orderInfo的获取必须来自服务端；
         */
        Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(payRequest, APPID);
        String orderParam = OrderInfoUtil2_0.buildOrderParam(params);
        String sign = OrderInfoUtil2_0.getSign(params, RSA_PRIVATE);
        final String orderInfo = orderParam + "&" + sign;

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(context);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                ALog.i("msp", result.toString());
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }


    @Override
    public void onInit(PaymentManager paymentManager) {
        paymentManager.registerPayAction(INSTANCE);
    }

}
